package com.example.demo2.common.config.security.fitler;

import com.alibaba.fastjson.JSON;
import com.example.demo2.common.config.redis.RedisUtil;
import com.example.demo2.common.jwt.JwtCreator;
import com.example.demo2.entity.SecurityUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class WebSecurityTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String token = request.getHeader("token");
        if(FilterUtils.securityExcludeUrl(requestURI)){
            filterChain.doFilter(request, response);
            return;
        }
        Claims tokenClaim = JwtCreator.getTokenClaim(token);

        if(Objects.isNull(tokenClaim)){
            filterChain.doFilter(request, response);
            return;
        }
        String subject = tokenClaim.getSubject();
        Object info = redisUtil.get(subject+":login");
        if(Objects.isNull(info)){
            throw new RuntimeException("用户信息为空");
        }

        SecurityUser user = JSON.parseObject(info.toString(), SecurityUser.class);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
